package cn.bonoon.kernel.web.handlers.loader;

import java.lang.reflect.AnnotatedElement;

import cn.bonoon.handler.AutoManager;
import cn.bonoon.kernel.events.ReadEvent;
import cn.bonoon.kernel.support.searcher.StandardFinder;
import cn.bonoon.kernel.support.services.ISearchable;
import cn.bonoon.kernel.web.annotations.AutoDataLoader;
import cn.bonoon.kernel.web.annotations.FinderFilter;

/**
 * <pre>
 * 子类用于自动生成的框架界面，包括以下几种类型的数据：
 * 1.datagrid列表
 *   1.1 分页加载{@link PageLoaderHandler}
 *   1.2 全部加载{@link ItemLoaderHandler}
 * 2.tree结构
 *   2.1 全部加载{@link PageLoaderHandler}未定义
 *   2.2 异步加载{@link PageLoaderHandler}未定义
 * 3.treegrid树列表
 *   3.1 全部加载{@link NodeLoaderHandler}
 *   3.2 异步加载{@link AjaxNodeLoaderHandler}
 * </pre>
 * 
 * 手动追加一些查询条件
 * @author jackson
 *
 */
public abstract class AbstractSearchableLoaderHandler extends AbstractLoaderHandler{
	protected Class<?> resultClass;
	
//	protected AbstractSearchableLoaderHandler(ISearchable searchable, Class<?> resultClass, AnnotatedElement aEle) throws Exception{
//		super(searchable.getSearcher(), searchable);
//		init(resultClass, aEle);
//	}

	protected AbstractSearchableLoaderHandler(ISearchable searchable, Class<?> resultClass, Class<?> queryClass, AnnotatedElement aEle) throws Exception{
		super(searchable.getSearcher(), searchable, queryClass);
		init(resultClass, aEle);
	}

//	public AbstractSearchableLoaderHandler(AutoManager manager, Class<?> resultClass, AutoDataLoader loader) throws Exception {
//		super(manager.getSesrcher(loader.value()), manager);
//		init(resultClass, loader);
//	}

	public AbstractSearchableLoaderHandler(AutoManager manager, Class<?> resultClass, Class<?> queryClass, AutoDataLoader loader) throws Exception {
		super(manager.getSesrcher(loader.value()), manager, queryClass);
		init(resultClass, loader);
	}

	private void init(Class<?> resultClass, AnnotatedElement aEle) {
		this.resultClass = resultClass;
		FinderFilter ff = aEle.getAnnotation(FinderFilter.class);
		if(null != ff){
			parseFilter(ff.useDefaultFilter(), ff.value(), aEle);
		}else{
			defaultFilter();
		}
	}

	private void init(Class<?> resultClass, AutoDataLoader loader) {
		this.resultClass = resultClass;
		parseFilter(loader.useDefaultFilter(), loader.filter(), resultClass);
	}

	@Override
	protected StandardFinder buildFinder(ReadEvent event) throws Exception {
		return searcher.finder(entityManager, event, resultClass);//autoManager.buildeExtendFinder(reader, event);
	}
	
}
